package atech.ace.mapping;

import java.io.IOException;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;

import atech.ace.mapping.persistence.entities.Company;
import atech.ace.mapping.persistence.entities.HumanResource;

/**
 * Servlet implementation class UpdateResource
 */
@WebServlet("/UpdateResource")
public class UpdateResource extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@PersistenceContext(name = "jdbc/ACE_ProjectMapping")
	EntityManager em;

	@Resource
	UserTransaction utx;
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
		String email = request.getParameter("email");
		String expertise = request.getParameter("expertise");
		String region = request.getParameter("region");
		boolean error = false;
		String[] errs = new String[0];
		try {
			utx.begin();
			HumanResource resource = em.find(HumanResource.class, id);
			resource.setFirstName(firstName);
			resource.setLastName(lastName);
			resource.setEmail(email);
			resource.setExpertise(expertise);
			resource.setRegion(region);
			errs = Validation.validateResource(resource);
			if(errs.length > 0)
				error = true;
			else
				em.merge(resource);
			utx.commit();
		} catch (Exception e) {
			try {
				e.printStackTrace();
				utx.rollback();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		if(error){
			request.setAttribute("updateErrs", errs);
			request.getRequestDispatcher("Create").forward(request, response);
		}else
			response.sendRedirect("Create");
	}

}
